<?php

namespace backend\models;

use Yii;
use yii\base\NotSupportedException;
use yii\db\ActiveRecord;
use yii\web\IdentityInterface;

/**
 * User model
 * @property integer $id
 * @property string  $username
 * @property string  $nickname
 * @property string  $admin_avatar
 * @property string  $password_hash
 * @property string  $password_reset_token
 * @property string  $email
 * @property string  $auth_key
 * @property integer $login_ip
 * @property string  $login_at
 * @property integer $login_num
 * @property integer $status
 * @property integer $created_at
 * @property integer $updated_at
 * @property array   $statusTexts
 */
class User extends ActiveRecord implements IdentityInterface
{

    const STATUS_DELETED = 0;
    const STATUS_ACTIVE  = 10;

    /**
     * @var array
     */
    public $switchValues = [
        'status' => [
            'on'  => 10,
            'off' => 0,
        ],
    ];

    /**
     * @var array
     */
    public $statusTexts = [
        0  => '禁用',
        10 => '启用',
    ];

    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'admin_user';
    }

    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            [['username', 'password_hash'], 'required'],
            [['status', 'login_ip', 'login_num'], 'integer'],
            ['status', 'default', 'value' => self::STATUS_ACTIVE],
            ['status', 'in', 'range' => [self::STATUS_ACTIVE, self::STATUS_DELETED]],
            [['login_at', 'updated_at', 'created_at'], 'safe'],
            [['username'], 'string', 'min' => 5, 'max' => 20],
            [['nickname'], 'string', 'min' => 2, 'max' => 20],
            [['password_hash'], 'string', 'min' => 6, 'max' => 255],
            [['password_reset_token', 'auth_key', 'admin_avatar'], 'string', 'max' => 255],
            [['email'], 'string', 'max' => 60],
            [['username'], 'unique'],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels()
    {
        return [
            'id'                   => '编号',
            'username'             => '账号',
            'nickname'             => '昵称',
            'password_hash'        => '密码',
            'password_reset_token' => '重置密码时的验证字串',
            'email'                => '邮箱',
            'auth_key'             => '使用cookie登陆的验证密钥',
            'admin_avatar'         => '头像',
            'login_ip'             => '登录ip',
            'login_at'             => '登录时间',
            'login_num'            => '登录次数',
            'status'               => '状态',//0禁止登陆，10允许登陆
            'updated_at'           => '更新时间',
            'created_at'           => '创建时间',
        ];
    }

    /**
     * @inheritdoc
     */
    public static function findIdentity($id)
    {
        return static::findOne(['id' => $id, 'status' => self::STATUS_ACTIVE]);
    }

    /**
     * findIdentityByAccessToken
     * @param mixed $token
     * @param null  $type
     * @return void|IdentityInterface
     * @throws NotSupportedException
     */
    public static function findIdentityByAccessToken($token, $type = null)
    {
        throw new NotSupportedException('"findIdentityByAccessToken" is not implemented.');
    }

    /**
     * Finds user by username
     * @param string $username
     * @return static|null
     */
    public static function findByUsername($username)
    {
        return static::findOne(['username' => $username, 'status' => self::STATUS_ACTIVE]);
    }

    /**
     * Finds user by password reset token
     * @param string $token password reset token
     * @return static|null
     */
    public static function findByPasswordResetToken($token)
    {
        if (!static::isPasswordResetTokenValid($token)) {
            return null;
        }

        return static::findOne([
            'password_reset_token' => $token,
            'status'               => self::STATUS_ACTIVE,
        ]);
    }

    /**
     * Finds out if password reset token is valid
     * @param string $token password reset token
     * @return bool
     */
    public static function isPasswordResetTokenValid($token)
    {
        if (empty($token)) {
            return false;
        }

        $timestamp = (int)substr($token, strrpos($token, '_') + 1);
        $expire    = Yii::$app->params['user.passwordResetTokenExpire'];
        return $timestamp + $expire >= time();
    }

    /**
     * @inheritdoc
     */
    public function getId()
    {
        return $this->getPrimaryKey();
    }

    /**
     * @inheritdoc
     */
    public function getAuthKey()
    {
        return $this->auth_key;
    }

    /**
     * @inheritdoc
     */
    public function validateAuthKey($authKey)
    {
        return $this->getAuthKey() === $authKey;
    }

    /**
     * Validates password
     * @param string $password password to validate
     * @return bool if password provided is valid for current user
     */
    public function validatePassword($password)
    {
        return Yii::$app->security->validatePassword($password, $this->password_hash);
    }

    /**
     * setPassword
     * Generates password hash from password and sets it to the model
     * @param $password
     * @throws \yii\base\Exception
     */
    public function setPassword($password)
    {
        $this->password_hash = Yii::$app->security->generatePasswordHash($password);
    }

    /**
     * generateAuthKey
     *  Generates "remember me" authentication key
     * @throws \yii\base\Exception
     */
    public function generateAuthKey()
    {
        $this->auth_key = Yii::$app->security->generateRandomString();
    }

    /**
     * Generates new password reset token
     * generatePasswordResetToken
     * @throws \yii\base\Exception
     */
    public function generatePasswordResetToken()
    {
        $this->password_reset_token = Yii::$app->security->generateRandomString() . '_' . time();
    }

    /**
     * Removes password reset token
     */
    public function removePasswordResetToken()
    {
        $this->password_reset_token = null;
    }

    /**
     * beforeSave
     * @param bool $insert
     * @return bool
     * @throws \yii\base\Exception
     */
    public function beforeSave($insert)
    {
        if ($insert) {
            $this->created_at = date('Y-m-d H:i:s');
            $this->setPassword($this->password_hash);
        } else {
            $this->getOldAttribute('password_hash') !== $this->password_hash && $this->setPassword($this->password_hash);
        }
        $this->updated_at = date('Y-m-d H:i:s');

        return parent::beforeSave($insert);
    }

    /**
     * afterLogin
     * @param $event
     */
    public static function afterLogin($event)
    {
        /** @var $user self */
        $user            = $event->identity;
        $user->login_ip  = ip2long(request()->getRemoteIP());
        $user->login_at  = date('Y-m-d H:i:s');
        $user->login_num += 1;
        $user->save(false);
    }

}
